package com.zeng.gitxuexi.sync;
//不安全买票 多个线程操作同一个对象，
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"苦逼的我").start();
        new Thread(station,"牛逼的你").start();
        new Thread(station,"可恶的黄牛党").start();
    }
}

class BuyTicket implements Runnable{
    //票
    private int ticketNums=10;
    boolean flag = true;
    @Override
    public  void run() {
        //买票
        while (flag){
            buy();
        }
    }
    //synchronized 同步方法，放在方法上 默认锁的是this 也就是锁的是BuyTicket的对象
    private synchronized void buy(){

        //判断是否有票
        if(ticketNums<=0){
            flag=false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到第"+ticketNums--);
    }
}